<?php

namespace app\api\controller;

use app\admin\service\WechatService;
use app\api\model\service\UserInfo;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Db;
use think\Log;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','save_wechat','setMpMenu','addMaterial'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }
    public function addMaterial(){
        $redata = \app\common\model\User::addMaterial();
        var_dump($redata);
    }
    /**
     * @return void
     * 设置公众号菜单
     */
    public function setMpMenu(){
        $APPID = 'wx52cc36ceaaf1f532';
        $arr['button'][0]['name'] = '找服务';
        $arr['button'][0]['sub_button'][0]['type'] = 'miniprogram';

        $arr['button'][0]['sub_button'][0]['name'] = '军式保洁';
        $arr['button'][0]['sub_button'][0]['url'] = 'pages/classify/classify';
        $arr['button'][0]['sub_button'][0]['appid'] = $APPID;
        $arr['button'][0]['sub_button'][0]['pagepath'] = 'pages/classify/classify';



        $arr['button'][0]['sub_button'][1]['type'] = 'miniprogram';
        $arr['button'][0]['sub_button'][1]['name'] = '家庭服务';
        $arr['button'][0]['sub_button'][1]['url'] = 'pages/classify/classify';
        $arr['button'][0]['sub_button'][1]['appid'] = $APPID;
        $arr['button'][0]['sub_button'][1]['pagepath'] = 'pages/classify/classify';

        $arr['button'][0]['sub_button'][2]['type'] = 'miniprogram';
        $arr['button'][0]['sub_button'][2]['name'] = '家电清洗';
        $arr['button'][0]['sub_button'][2]['url'] = 'pages/classify/classify';
        $arr['button'][0]['sub_button'][2]['appid'] = $APPID;
        $arr['button'][0]['sub_button'][2]['pagepath'] = 'pages/classify/classify';

        $arr['button'][0]['sub_button'][3]['type'] = 'miniprogram';
        $arr['button'][0]['sub_button'][3]['name'] = '养老护理';
        $arr['button'][0]['sub_button'][3]['url'] = 'pages/classify/classify';
        $arr['button'][0]['sub_button'][3]['appid'] = $APPID;
        $arr['button'][0]['sub_button'][3]['pagepath'] = 'pages/classify/classify';

        $arr['button'][0]['sub_button'][4]['type'] = 'miniprogram';
        $arr['button'][0]['sub_button'][4]['name'] = '更多直营服务';
        $arr['button'][0]['sub_button'][4]['url'] = 'pages/index/index';
        $arr['button'][0]['sub_button'][4]['appid'] = $APPID;
        $arr['button'][0]['sub_button'][4]['pagepath'] = 'pages/index/index';

        $arr['button'][1]['name'] = '限时优惠';
        $arr['button'][1]['sub_button'][0]['type'] = 'miniprogram';
        $arr['button'][1]['sub_button'][0]['name'] = '空调清洗29.9元';
        $arr['button'][1]['sub_button'][0]['url'] = 'service/servedetail/servedetail?id=111';
        $arr['button'][1]['sub_button'][0]['appid'] = $APPID;
        $arr['button'][1]['sub_button'][0]['pagepath'] = 'service/servedetail/servedetail?id=111';

        $arr['button'][1]['sub_button'][1]['type'] = 'miniprogram';
        $arr['button'][1]['sub_button'][1]['name'] = '军式开荒15元/平';
        $arr['button'][1]['sub_button'][1]['url'] = 'service/servedetail/servedetail?id=38';
        $arr['button'][1]['sub_button'][1]['appid'] = $APPID;
        $arr['button'][1]['sub_button'][1]['pagepath'] = 'service/servedetail/servedetail?id=38';

        $arr['button'][1]['sub_button'][2]['type'] = 'miniprogram';
        $arr['button'][1]['sub_button'][2]['name'] = '油烟机+洗衣机198元';
        $arr['button'][1]['sub_button'][2]['url'] = 'service/servedetail/servedetail?id=115';
        $arr['button'][1]['sub_button'][2]['appid'] = $APPID;
        $arr['button'][1]['sub_button'][2]['pagepath'] = 'service/servedetail/servedetail?id=115';

        $arr['button'][1]['sub_button'][3]['type'] = 'miniprogram';
        $arr['button'][1]['sub_button'][3]['name'] = '深度保洁3小时立减200';
        $arr['button'][1]['sub_button'][3]['url'] = 'service/servedetail/servedetail?id=112';
        $arr['button'][1]['sub_button'][3]['appid'] = $APPID;
        $arr['button'][1]['sub_button'][3]['pagepath'] = 'service/servedetail/servedetail?id=112';

        $arr['button'][1]['sub_button'][4]['type'] = 'miniprogram';
        $arr['button'][1]['sub_button'][4]['name'] = '幸运大转盘';
        $arr['button'][1]['sub_button'][4]['url'] = 'service/dial/dial';
        $arr['button'][1]['sub_button'][4]['appid'] = $APPID;
        $arr['button'][1]['sub_button'][4]['pagepath'] = 'service/dial/dial';

        $arr['button'][2]['name'] = '更多服务';
        $arr['button'][2]['sub_button'][0]['type'] = 'media_id';
        $arr['button'][2]['sub_button'][0]['name'] = '立即预约';
        $arr['button'][2]['sub_button'][0]['media_id'] = 'rHDTmrK1QJc5N3biIuAiyy3nNPvolPsw4qZIp2Dz_eulGKO3AuVCWFpSmPJ05XVP';
        $arr['button'][2]['sub_button'][1]['type'] = 'media_id';
        $arr['button'][2]['sub_button'][1]['name'] = '工程咨询';
        $arr['button'][2]['sub_button'][1]['media_id'] = 'rHDTmrK1QJc5N3biIuAiyy3nNPvolPsw4qZIp2Dz_eulGKO3AuVCWFpSmPJ05XVP';
        $arr['button'][2]['sub_button'][2]['type'] = 'media_id';
        $arr['button'][2]['sub_button'][2]['name'] = '商务合作';
        $arr['button'][2]['sub_button'][2]['media_id'] = 'rHDTmrK1QJc5N3biIuAiyy3nNPvolPsw4qZIp2Dz_eulGKO3AuVCWFpSmPJ05XVP';
        $arr['button'][2]['sub_button'][3]['type'] = 'media_id';
        $arr['button'][2]['sub_button'][3]['name'] = '课程培训';
        $arr['button'][2]['sub_button'][3]['media_id'] = 'rHDTmrK1QJc5N3biIuAiyy3nNPvolPsw4qZIp2Dz_eulGKO3AuVCWFpSmPJ05XVP';
        $arr['button'][2]['sub_button'][4]['type'] = 'media_id';
        $arr['button'][2]['sub_button'][4]['name'] = '招聘信息';
        $arr['button'][2]['sub_button'][4]['media_id'] = 'rHDTmrK1QJc5N3biIuAiyy3nNPvolPsw4qZIp2Dz_eulGKO3AuVCWFpSmPJ05XVP';

        $param = json_encode($arr,JSON_UNESCAPED_UNICODE);
        try {
            $redata = \app\common\model\User::sendsetMpMenu($param);
            var_dump($redata);
            $msg = '推送成功';
        } catch (\Exception $e) {
            $msg = $e->getCode() == '43004' ? '没有关注该服务号' : $e->getMessage();
        }
        Log::write("设置公众号菜单：".json_encode($param)."__appid_data:".json_encode($msg));
        echo $param;
        echo json_encode($msg);
    }
    /**
     * @return false|void
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * 关注公众号获取公众号openid
     */
    public function save_wechat()
    {
        //先获取到这三个参数
        $signature = $_GET['signature'];
        $postStr = file_get_contents("php://input");
        $this->responseMsg($postStr);
        $nonce = $_GET['nonce'];
        $timestamp = $_GET['timestamp'];
        //把这三个参数存到一个数组里面
        $tmpArr = array($timestamp,$nonce,'jiazheng');
        //进行字典排序
        sort($tmpArr,SORT_STRING);

        //把数组中的元素合并成字符串，impode()函数是用来将一个数组合并成字符串的
        $tmpStr = implode($tmpArr);

        //sha1加密，调用sha1函数
        $tmpStr = sha1($tmpStr);

        //判断加密后的字符串是否和signature相等
        if($tmpStr == $signature)
        {
            $openid = $_GET['openid'];
            $re_data = \app\common\model\User::getAuthAccessToken($openid);
            //$re_data = json_decode($re_data,true);
            Db::name("service_user_info")->where(['unionid'=>$re_data['unionid']])->update(['mp_openid'=>$openid]);
           // echo $echostr;
           exit();
        }

        return false;

    }
    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if($captcha != '6666'){
            if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
                $this->error(__('Captcha is incorrect'));
            }
        }

        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
            if ($ret) {
                $uid = $this->auth->id;
                $newUser = ['user_id' => $uid, 'mobile' => $mobile];
                $userInfo = new UserInfo($newUser);
                $userInfo->allowField(true)->save();
            }
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['user' => $this->auth->getUserinfo(),'userInfo'=>UserInfo::getInfo($this->auth->id)];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    public function responseMsg($postStr)
    {
        //$postStr = file_get_contents("php://input");
        if (!empty($postStr)){

            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

            $result = "";
            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
            }
            echo $result;
        }else {
            echo "";
            exit;
        }
    }

    private function receiveEvent($object)
    {
        switch ($object->Event)
        {
            case "subscribe":
                $content = "欢迎关注方倍工作室 ";

            //------------------- 赞一下 start ------------------------
            case "CLICK":   //这里是大写‘CLICK’

                $content = $object->EventKey; // 获取key

                if($content=='rselfmenu_0_0'){

                    $content = '正在装修中~~~即将赶来~~敬请期待!';

                }
                //------------------- 赞一下 end ------------------------

                break;
        }
        $result = $this->transmitText($object, $content);
        return $result;
    }

    private function receiveText($object)
    {
        $keyword = trim($object->Content);

        $url = "http://apix.sinaapp.com/weather/?appkey=".$object->ToUserName."&city=".urlencode($keyword);
        $output = file_get_contents($url);
        $content = json_decode($output, true);

        $result = $this->transmitNews($object, $content);

        return $result;
    }

    private function transmitText($object, $content)
    {
        if (!isset($content) || empty($content)){
            return "";
        }
        $textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
        $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
        return $result;
    }

    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return "";
        }
        $itemTpl = "<item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
        </item>
        ";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[]]></Content>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";

        $result = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }
}
